<script setup lang="tsx">
import { NButton, NPopconfirm, NSpace, NSwitch } from "naive-ui";
import type { DataTableColumns, FormInst } from "naive-ui";
import TableModal from "./components/TableModal.vue";

import {
  changeUserStatus,
  delUser,
  fetchUserList,
  getRole,
  selectRoleList,
  upRole,
} from "@/service/api/user";
import { useBoolean, useLoading } from "@/hooks";

const userList = ref([]);
const roleList = ref([]);
const formRef = ref<FormInst | null>();
const formRoleRef = ref<FormInst | null>();
const initialParams = {
  pageNum: 1,
  pageSize: 10,
  userName: "",
  nickName: "",
};
const params = ref({ ...initialParams });
const total = ref(0);
const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean(false);
const openRole = ref(false);
type ModalType = "add" | "edit";
const modalType = ref<ModalType>("add");
const editData = ref<CommonList.UserList | null>(null);

const columns: DataTableColumns = [
  {
    title: "用户名",
    align: "center",
    key: "userName",
  },
  {
    title: "昵称",
    align: "center",
    key: "nickName",
  },
  {
    title: "登录IP",
    align: "center",
    key: "loginIp",
  },
  {
    title: "手机号码",
    align: "center",
    key: "phonenumber",
  },
  {
    title: "创建时间",
    align: "center",
    key: "createTime",
  },
  {
    title: "状态",
    align: "center",
    key: "status",
    render: (row) => {
      const rowData = (row as unknown) as CommonList.UserList;
      if (rowData.admin) return null;
      return (
        <NSwitch
          value={rowData.status}
          checkedValue={"0"}
          onUpdateValue={(status) => handleStatusChange(rowData.userId, status)}
        >
          {{ checked: () => "启用", unchecked: () => "禁用" }}
        </NSwitch>
      );
    },
  },
  {
    title: "操作",
    align: "center",
    key: "actions",
    render: (row) => {
      const rowData = (row as unknown) as CommonList.UserList;
      if (rowData.admin) return null;
      return (
        <NSpace justify="center">
          <NButton size="small" type="info" onClick={() => handleEditRole(rowData)}>
            角色
          </NButton>
          <NButton size="small" type="warning" onClick={() => handleEditTable(rowData)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => sendMail(rowData.userName, rowData.userId)}>
            {{
              default: () => "确认删除",
              trigger: () => (
                <NButton size="small" type="error">
                  删除
                </NButton>
              ),
            }}
          </NPopconfirm>
        </NSpace>
      );
    },
  },
];
const formRole = ref({
  userId: undefined,
  roleIds: [],
});
// 列表
async function getUserList() {
  startLoading();
  await fetchUserList(params.value).then((res: any) => {
    userList.value = res.rows;
    total.value = res.total;
    endLoading();
  });
}
// 编辑
function handleEditTable(rowData: any) {
  setEditData(rowData);
  setModalType("edit");
  openModal();
}
// 添加
function handleAddTable() {
  openModal();
  setModalType("add");
}
// 检索
function handleQuery() {
  params.value.pageNum = 1;
  getUserList();
}
// 重置
function handleResetSearch() {
  params.value = { ...initialParams };
  getUserList();
}
// 分页
function changePage(page: number, size: number) {
  params.value.pageNum = page;
  params.value.pageSize = size;
  getUserList();
}
// 修改状态
function handleStatusChange(userId: number, status: boolean) {
  const s = status === false ? "1" : "0";
  const text = s === "0" ? "启用" : "禁用";
  window.$dialog.warning({
    title: `提醒`,
    content: `确定要${text}该用户吗？`,
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      changeUserStatus(userId, s).then(() => {
        window.$message.success(`${text}成功`);
        getUserList();
      });
    },
    onNegativeClick: () => {
      status = s === "0";
    },
  });
}
//
function setModalType(type: ModalType) {
  modalType.value = type;
}
function setEditData(data: any | null) {
  editData.value = data;
}
// 设置角色
function handleEditRole(row: any) {
  formRole.value.userId = row.userId;
  openRole.value = true;
  getRoleList();
  getRoleInfo(row.userId);
}
// 查询角色信息
async function getRoleInfo(userId: number) {
  await getRole(userId).then((response: any) => {
    const roleIds: number[] = [];
    if (response.user.roles.length > 0) {
      response.user.roles.forEach((item: any) => {
        roleIds.push(item.roleId);
      });
    }
    formRole.value.roleIds = roleIds;
  });
}
// 查询角色列表
async function getRoleList() {
  await selectRoleList().then((response: any) => {
    roleList.value = response.data;
  });
}
// 分配角色
function handleSaveRole() {
  if (formRole.value.roleIds.length > 0) {
    const data = {
      userId: formRole.value.userId,
      roleIds: formRole.value.roleIds.toString(),
    };
    upRole(data).then(() => {
      window.$message.success("分配成功");
      openRole.value = false;
    });
  }
}
function sendMail(userName: string, userId: number) {
  delUser(userId).then(() => {
    window.$message.success(`删除用户:${userName}`);

    getUserList();
  });
}
function handleRefresh() {
  getUserList();
}
getUserList();
</script>

<template>
  <NSpace vertical size="large">
    <n-card>
      <n-form ref="formRef" :model="params" label-placement="left" :show-feedback="false">
        <n-grid :x-gap="30" :cols="4">
          <n-form-item-gi label="用户名" path="userName">
            <n-input v-model:value="params.userName" placeholder="请输入" />
          </n-form-item-gi>
          <n-form-item-gi label="昵称" path="nickName">
            <n-input v-model:value="params.nickName" placeholder="请输入" />
          </n-form-item-gi>
          <n-form-item-gi>
            <NButton type="primary" @click="handleQuery">
              <template #icon>
                <icon-park-outline-search />
              </template>
              搜索
            </NButton>
            <NButton strong secondary @click="handleResetSearch">
              <template #icon>
                <icon-park-outline-redo />
              </template>
              重置
            </NButton>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-card>
    <n-card>
      <NSpace vertical size="large">
        <div class="flex gap-4">
          <NButton type="primary" @click="handleAddTable">
            <template #icon>
              <icon-park-outline-add-one />
            </template>
            新建
          </NButton>
        </div>
        <n-data-table :columns="columns" :data="userList" :loading="loading" />
        <Pagination :count="total" @change="changePage" v-if="total > params.pageSize" />
        <TableModal
          v-model:visible="visible"
          :type="modalType"
          :modal-data="editData"
          @refresh="handleRefresh"
        />
        <!-- 角色弹框 -->
        <n-modal
          v-model:show="openRole"
          :mask-closable="false"
          preset="card"
          title="分配角色"
          class="w-500px"
          :segmented="{
            content: true,
            action: true,
          }"
        >
          <n-form
            label-placement="left"
            ref="formRoleRef"
            :model="formRole"
            label-align="left"
            :label-width="80"
          >
            <n-grid :cols="24" :x-gap="18">
              <n-form-item-grid-item :span="24" label="角色" path="roleIds">
                <n-select
                  v-model:value="formRole.roleIds"
                  multiple
                  :options="roleList"
                  filterable
                  label-field="roleName"
                  value-field="roleId"
                />
              </n-form-item-grid-item>
            </n-grid>
          </n-form>
          <template #action>
            <n-space justify="center">
              <n-button @click="openRole = false"> 取消 </n-button>
              <n-button type="primary" @click="handleSaveRole"> 提交 </n-button>
            </n-space>
          </template>
        </n-modal>
      </NSpace>
    </n-card>
  </NSpace>
</template>
